<template>
  <Layout>

           <!--通话管理-->
        <Modal
                v-model="showManagementView"
                :closable=false
                :mask-closable="false"
                :width="1200"
                title="查看通话">
                <monitoring @joinSession="joinSession"></monitoring>
            <div slot="footer">
                <Button type="info" size="default"  class="defaultbackColor" @click="showManagementView = false">确定</Button>
            </div>
        </Modal>

    <!--<remote-hand-sign class="handsign"></remote-hand-sign>-->
    <screensharemark class="screenmark" v-show="showscreenmark" @closescreenmark="closescreenmark"></screensharemark>
    <Header style="background-color: rgba(44, 137, 234, 1);">
      <audio src="../../static/ring.wav" loop id="ringaudio"></audio>
      <div>
        <watermark-replacebackground :width="resolution.width"  :height="resolution.height" :aitype="aitype" :resolution="resolution"
                                     :isAddWatermark="isAddWatermark" :isReplaceBackground="isReplaceBackground" :Red="Red"  :Green="Green" :Blue="Blue"
                                     ref="wmrbg" @publishwmrbgstream="publishwmrbgstream" @createstreamerror="createstreamerror"
        >

        </watermark-replacebackground>
        <span class="headtitle">工号:{{agentId}}</span>
        <img src="../../static/images/setting.png" class="setting" @click="showsetting=true">

        <headop class="z-headop" :localpublication="localPublication" :agentlogin="islogin"  :agentotherwork="isotherwork"
                :agentready="isready" :agentskill="skillvalue" :sessionId="sessionId" :audiomuted="audiomuted"
                :appointvalue="appointvalue" @sessionManagement="sessionManagement"
                @login="agentlogin" @otherwork="otherwork" @appoint="appoint"  @agentaudio="audioop"
                @logout="agentlogout" @ready="agentready" @unready="agentunready" @setskill="setskill"
        ></headop>

        <Modal
          v-model="onRing"
          :closable=false
          title="温馨提示"
          ok-text="接听"
          cancel-text="拒绝"
          @on-ok="answercall"
          @on-cancel="rejectcall">
          <div style="font-size: 14px">你被分配到访客</div>
        </Modal>




      </div>

      <settings class="settingview" @setresolution="setresolution"
                @setbirtate="setbirtate" @addbackgroup="addbackgroup"
                @addwater="addwater" @close="showsetting=false" v-show="showsetting">
      </settings>
    </Header>

    <div class="videoshow"  ref="div">
      <Row type="flex" justify="start" style="width: 100%">
        <div id="cameraView">
          <video id="cameraVid" autoplay hidden style="display:none"></video>
          <audio id="cameraAid" autoplay hidden></audio>
        </div>
        <div id="customerview" style="width: 60%">
          <div v-show="!customershow" class="defaultcustomer">
            <img src="../../static/images/renwu.png" class="customerrenwu">
          </div>
          <video class="customervideo"  controls playsinline autoplay   id="customer" v-show="customershow"></video>
        </div>

        <!--<div class="otherStream" v-show="aishow||ai2show">-->
          <!--<video  class="otherStreamvideo" playsinline autoplay muted controls id="ai"  v-show="aishow"></video>-->
          <!--<video  class="otherStreamvideo" playsinline autoplay muted controls id="ai2" v-show="ai2show"></video>-->
          <!--<video class="otherStreamvideo" controls playsinline autoplay muted id="screen" v-show="screenstreampublication"></video>-->
          <!--<video class="otherStreamvideo" controls playsinline autoplay muted id="screenapp" v-show="screenappstreampublication"></video>-->
        <!--</div>-->
        <div class="otherStream">

          <div v-for="item in agentstreams">
            <!--<video  class="otherStreamvideo" playsinline autoplay muted controls :id="item.id"></video>-->
            <video  class="otherStreamvideo" controls playsinline autoplay muted :id="item.id" v-if="localStreamId&&localStreamId==item.id"></video>
            <video  class="otherStreamvideo" controls playsinline autoplay :id="item.id" v-else></video>
          </div>

          <div v-show="agentstreams.length==0" class="defaultagent">
            <div class="agentdiv">
              <img src="../../static/images/renwu.png" class="agentrenwu">
            </div>
            <div class="agentdiv">
              <img src="../../static/images/renwu.png" class="agentrenwu">
            </div>
          </div>

          <video class="otherStreamvideo" controls playsinline autoplay muted id="screen" v-show="screenstreampublication||screenstream"></video>
          <video class="otherStreamvideo" controls playsinline autoplay muted id="screenapp" v-show="screenappstreampublication"></video>
        </div>

      </Row>
    </div>

    <Content style="height: 700px">
      <Row style="height: 600px;width: 100%">
        <Col span="7" style="background-color: whitesmoke">
          <AILeft :data="forminfodata" :formdata="formdata"  ref="aileft" @collectionPic="collectionPic"
                   @collectionform="collectionform" @getformdata="getformdata"></AILeft>
        </Col>
        <Col span="11" style="height: 500px;">
          <AgentOp  ref="agentop" style="margin-top: 368px" @endsession="endsession" @screen="screenshare" @remove="removeAgent"
                   @transfer="tranferagent(true)" @photoGuideBox="photoGuideBox"  @screenmark="screenmark"
                   @recordscreen="recordscreen" @stopscreen="stopscreen" @three="tranferagent(false)" :isConsulting="isConsulting"
                    @snapshot="snapshot"  @sendlink="sendlink" @sendvideo="sendvideo" @videoCall="videoCall" @stopConsulting="stopConsulting"
                   :screenstreampublication="screenstreampublication" :screenstream="screenstream" @consulting="consulting"
                    :screenappstreampublication="screenappstreampublication"> 
          </AgentOp>
          <!--</Row>-->
        </Col>
        <Col span="6">
          <right ref="right" @getforminfodata="getforminfodata" :captureImage="captureImage" :recorddata="recorddata"
                  :chatList="chatList"   @getformdata="getformdata" @customerhangup="customerhangup" :formdata="formdata"
          ></right>
        </Col>
      </Row>
    </Content>
    <!--<Footer style="background:rgba(229,229,229,1);color:rgba(164,164,164,1);font-size: 16px">© 2019HomeCredit版权所有</Footer>-->
  </Layout>
</template>

<script>

  import Right from "./Right";
  import arraytool from '../tool/tool'
  import {createmediaStream,publishlocalstream,createscreenstream,publishscreenstream} from "../tool/tool";
  import imchat from '../tool/imchat'
  import AILeft from "./AILeft";
  import AgentOp from "./AgentOp";
  import Settings from "./Settings";
  import Userinfo from "./Userinfo";
  import Transfer from "./Toast/Transfer"
  import SendLink from "./Toast/SendLink";
  import SendVideo from "./Toast/SendVideo";
  import watermark from "./Toast/WaterMark";
  import bg from "./Toast/BG";
  import SkillList from './Toast/SkillList';
  import Appointment from './Toast/Appointment';
  import Otherwork from './Toast/Otherwork';
  import {getuserforminfo,getsessionformdata,saveimg,updateskill,stoprecording,startrecord,addmix,savesessionform,streamoutmystream,streaminrtmp} from "../api/api";
  import WatermarkReplacebackground from "./WatermarkReplacebackground";
  import Screensharemark from "./Screensharemark";
  import message from '../../static/js/message';
  import Headop from "./Headop";
  import RemoteHandSign from "./Toast/RemoteHandSign";

  import {retrieveImageFromClipboardAsBase64} from "../tool/util";
import Monitoring from '../Monitoring/Monitoring.vue';

  export default {
    name: "Agent",
    components: {
      RemoteHandSign,
      Headop, Screensharemark, WatermarkReplacebackground, Settings,
      AgentOp, AILeft, Right,Userinfo,SendLink,SendVideo,watermark,
        Monitoring},
    data(){
      return {
        showManagementView:false,//是否查看通话记录
        isConsulting:false,//是否在咨询中
        showsetting:false,
        customershow:false,
        showscreenmark:false,
        onRing:false,//是否振铃了
        isReplaceBackground:false,
        isAddWatermark:false,
        isready: false,//是否就绪
        islogin:false,
        isotherwork:false,//是否是小休状态
        isappoint:false,//是否是预约后状态
        resolution: {
          width: 640,
          height: 480
        },//分辨率
        maxBitrate: 512,//推送的码率
        aitype:'ai',
        Red:100,
        Green:100,
        Blue:100,

        formdata:null,//客户在线表单信息
        forminfodata:null,//客户提前填好的信息
        participant:null,
        agentstreams:new Array(),
        userId: null,//访客id
        username:null,
        roomId:null,
        roomToken: null,//坐席创建的房间的token,
        localStream: null,//坐席自己的流
        localStreamId: null,//坐席自己的流id
        localPublication:null,
        screenstream: null,//坐席共享的流或者监听到其他坐席共享的流
        screenstreampublication: null,//坐席分享流的管理publication
        screenappstream: null,//坐席共享的app流
        screenappstreampublication: null,//坐席分享app流的管理publication
        recorddata: [],//会话过程中的数据
        chatList: [],
        captureImage:null,//拍客户端的照片
        audiomuted:false,//坐席是否静音
        roomresp:null,//房间里面的内容
        recordstreamList:[],//在录制的流的recordid合集
        icsClient:null,
        ccsurl:null,
        sessionId:null,
        agentId:null,
        clientId:null,
        angetClient:null,
        ticket:null,
        sessiondata:null,//当前会话的数据
        userData:null,
        otherworkreason:null,//小休原因
        skillvalue:null,//坐席选择的技能
        appointvalue:null,//预约的内容
        amsinterval:null,
        isHandSign:false,
        customerClientInfo:'web',//默认来自web_h5
      }
    },

    /*初始化*/
    mounted() {
      this.bindMove(this);
      /*IM 通知坐席加入房间*/
      var self = this;
      message.$on('sendwhiteboard',function (message) {
           self.sendwhiteboardmessage(message);
      });
      imchat.$on('agentjoinroom',function (resp) {
        self.roomId = resp.roomId;
        self.roomToken = resp.roomToken;
        self.clientId = resp.clientId;
        console.log('roomid===',self.roomId);
        console.log('roomtoken===',self.roomToken);
        console.log('clientId===',self.clientId);
        var clientInfo;
        for(let i = 0;i<resp.members.length;i++){
          var member = resp.members[i];
          if(member.role == 'customer'){
            if(member.clientInfo){
              clientInfo = member.clientInfo;
              self.customerClientInfo = clientInfo.type;
            }
          }
        }
        console.log('customer clientInfo,',clientInfo);
        self.joinroom();
      });

      imchat.$on('handwriting',function (code) {
        if (!self.isHandSign){
          self.showhandSign(code);
          self.isHandSign = true;
        }
      });

      imchat.$on('getforminfo',function (formid) {
         self.getforminfodata(formid);
      });

      imchat.$on('systemDropAgent',()=>{
          self.quitCurrentSession();
          self.$Notice.info({
          title: '温馨提示',
          desc: '您被剔除当前会话',
          duration:10
        });
      });

      imchat.$on('transferLeave',()=>{
         self.quitCurrentSession();
      })

      imchat.$on('inputformsuccess',function () {
        self.$Notice.success({
          title: '温馨提示',
          desc: '访客表单成功提交，可点击用户文件区域的获取表单按钮查看访客提交的表单信息',
          duration:10
        });
      });


      imchat.$on('customerhangup',function () {
        self.customerhangup();
      });


      imchat.$on('customerjoinroomerror',function(){
         self.customerjoinroomerror();
      });

      imchat.$on('resumeconnectwithccsfailed',function () {
         //ccs连接失败
         self.quitCurrentSession();
      });

      imchat.$on('collectionPicfailed',function(){
        self.$Message.error('图片采集失败～,请稍后再试');
      });

      imchat.$on('holdonsuccess',function () {
        //转接成功，坐席端的操作
        self.quitCurrentSession();
      });

      imchat.$on('dropsession',function () {
          //session drop
          self.quitCurrentSession();
      });


      window.addEventListener("paste", function(e){
        // Handle the event
        retrieveImageFromClipboardAsBase64(e, function(imageDataBase64){
          // If there's an image, open it in the browser as a new window :)
          if(imageDataBase64){
            console.log(imageDataBase64);
           // window.open(imageDataBase64);
          }
        });
      }, false);

      /**
       * 页面触发 onbeforeunload 事件时进入
       * 1）在页面被关闭前会进入
       * 2）方法有返回值时才会弹框
       * 3）方法返回的值与页面最终是否被关闭无关，即返回什么值都不会影响
       */
      window.onbeforeunload = function (event) {
        console.log("准备离开网页：" + new Date());
        /**
         * 因为 js 是阻塞执行的，所以在弹窗提示用户是否离开页面的时候，setTimeout 延迟不会执行
         * 一直等到用户选择 离开 还是 取消后，才会执行 setTimeout 延迟，延迟 1 秒调用方法
         * 如果用户选择的是离开，则 1 秒之后，早已经离开，不会影响；如果用户选择的是取消，则 1秒后会执行下面的方法
         */
        setTimeout(beforeloadResult, 1000);
        event.returnValue = "";
      };

      /**
       * 只要能进入此方法，则表示用户并没有离开页面
       */
      function beforeloadResult() {
        console.log("not leave：" + new Date());
      }

      window.addEventListener('unload', function() {
        //窗口关闭后执行
        clearInterval(self.amsinterval);
        self.amsinterval = null;
        if (self.sessionId){
          self.endsession();
        }
        if (self.islogin){
          self.agentlogout();
        }
        imchat.$off('agentjoinroom');
        imchat.$off('getforminfo');
        imchat.$off('customerhangup');
        imchat.$off('customerjoinroomerror');
        imchat.$off('collectionPicfailed');
      });





    },
    destroyed(){
      this.$Message.info('你已离开!');
      clearInterval(this.amsinterval);
      this.amsinterval = null;
      if (this.sessionId){
        this.endsession();
      }
      if (this.islogin){
        this.agentlogout();
      }
      imchat.$off('agentjoinroom');
      imchat.$off('getforminfo');
      imchat.$off('customerhangup');
      imchat.$off('customerjoinroomerror');
      imchat.$off('collectionPicfailed');
      window.location.reload(); //刷新当前页面.
    },
    methods:{

    /**
    * 通话管理
    */
    sessionManagement(){
       this.showManagementView = true;
    },

     /**
      * 语音转视频
      */
     videoCall(){
          if(this.userData.media == 'audio'){
            this.removepublicationEvent(this.localPublication);
             this.localPublication.stop();
             if (this.localStream){
              console.log(this.localStream);
              console.log(this.localStream.mediaStream);
              if (this.localStream.mediaStream){
                this.stopTrack(this.localStream.mediaStream)
                this.localStream = null;
              }else{
                this.stopTrack(this.localStream)
                this.localStream = null;
              }
            }
            this.agentstreams = arraytool.removeArraybyoriginid(this.agentstreams,this.localPublication);
            console.log('audio to video agent streams',this.agentstreams);
            this.userData.media = "video";
            imchat.$emit('sendCustomText','startAudioToVideo');
            this.setstreamandpublish();
          }else{
             this.$Message.info('当前已经是视频通话');
          }
     },

     stopTrack(medias) {
        medias.getTracks().forEach(track => {
            track.stop()
            console.log('关闭摄像头成功', new Date());
        })
      },
      /*zealcomm1:ics-mcu*/
     sendwhiteboardmessage(message){
        this.icsClient.send(message,undefined).then(function (resp) {
          console.log('send white board success');
          console.log(resp)
        }).catch(function (error) {
          console.log(error)
        })
      },

      /*加入房间*/
      joinroom(){
        console.log(typeof(this.roomToken));
        console.log('roomtoken=',this.roomToken);
        let {ConferenceClient} = IRtc.Conference;
        let turnserverUrl = localStorage.getItem('turnserverUrl');
        let turnserverCredential = localStorage.getItem('turnserverCredential');
        let turnserverUsername = localStorage.getItem('turnserverUsername');
        /*设置turn server*/
        let ccOptions = {
          rtcConfiguration: {
            iceServers: [{
              urls: [
                turnserverUrl
              ],
              credential: turnserverCredential,
              username: turnserverUsername
            }]
          }
        };

        this.icsClient = new ConferenceClient();

        var self = this;
        this.icsClient.join(this.roomToken).then(function (resp) {
          console.log('join  success:', resp);
          self.roomresp = resp;
          //用户当前自己的用户信息
          let i = resp.participants.length;
          if (i>0){
            self.participant = resp.participants[i-1];
            console.log('now user is',self.participant);
          }
          //录制mix流
          self.recordstream(resp.remoteStreams[0].id,resp.remoteStreams[0].id);
          self.addclientEvent(self.icsClient);
          self.setstreamandpublish();
        }).catch(function (error) {
          imchat.$emit('agenttellcustomer',{id:"agentId",status:'agenterror'});
          self.quitCurrentSession();
          console.log(error)
        })
      },

      //创建流并publish
      setstreamandpublish(){
        var self = this;
        if (self.isAddWatermark||self.isReplaceBackground){
          self.$refs.wmrbg.createwaterstream();
        } else{
          let isAudio = true;
          let isVideo = true;
          //判断是否是音频呼叫
          if(this.userData && this.userData.media === 'audio'){
               isVideo = false;
          }
          createmediaStream(isVideo,isAudio,self.resolution,self.aitype).then(function (localStream) {
            self.localStream = localStream;
            self.aipublishlocalStream(self.localStream,self.aitype);
          }).catch(function (error) {
            console.log(error);
            self.createstreamerror();
          });
        }
      },


      streamout(streamId,streamoutUrl,isScreenStream){
        var audio = isScreenStream?false:{
          "from":streamId
        };
        let para = {
          "media":
            {
              "audio":audio,
              "video":
                {
                  "from":streamId
                }
            },
          "url":streamoutUrl
        };
        var self = this;
        streamoutmystream(self.roomId,para).then(function (resp) {
          console.log(resp)
          if (resp.status == 200){
              if(isScreenStream){
                imchat.$emit('screenshare','start');
              }
          }else{
             self.quitCurrentSession();
          }
        }).catch(function (error) {
          self.quitCurrentSession();
        })
      },


      /*停止录制*/
      stoprecordstream(recordid){
        stoprecording(this.roomId,recordid).then(function (resp) {
          if (resp.status == 200){
          } else{
            console.log('record failed');
          }
        }).catch(function (error) {
          console.log('record failed',error);
        })
      },

      /*TODO 录制stream*/
      recordstream(audiostreamId,videostreamId){
        let url = "/ivcs/api/v1/rooms/"+this.roomId+'/recordings';
        let audio = audiostreamId?{"from":audiostreamId}:false;
        let para = {
          "container":"auto",
          "media":{
            "audio":audio,
            "video": {
              "from": videostreamId
            }
          }
        }
        var self = this;
        console.log('start record stream',audiostreamId,videostreamId);
        startrecord(url,para).then(function (resp) {
          console.log('stream record success with result:',resp);
          if (resp.status == 200){
            self.recordstreamList.push(resp.data.id);
           // self.$Message.success('录制成功',videostreamId);
          } else{
            self.$Message.error('开始录制失败',videostreamId);
          }
        }).catch(function (error) {
          console.log('record stream failed',error);
          self.$Message.error('开始录制失败',error);
        });
      },

      /*录屏*/
      recordscreen(){
        if (this.icsClient){
          var self = this;
          createscreenstream("airecordscreen").then(function (screenstream) {
            let videoCodec = {
              name: 'h264',
            }
            let  video = [{
              codec:videoCodec,
              maxBitrate:800,//vga 800, 720 2000, 1080 4000
            }]
            let audio = false;
            let option = {
              audio: audio,
              video: video,
            };
            publishscreenstream(self.icsClient,screenstream,option).then(function (publication) {
              self.recordstream(null,publication.id);
            }).catch(function (error) {
              console.log('publish record screen stream failed: ', error);
            })
          })
        } else{
          this.$Message.error("暂不支持");
        }
      },

      /*client leave*/
      leaveclient(){
        this.removepublicationEvent(this.localPublication);
        if (this.icsClient){
          this.icsClient.clearEventListener("streamadded");
          this.icsClient.clearEventListener("serverdisconnected");
          this.icsClient.clearEventListener("participantjoined");
          var self = this;
          this.icsClient.leave().then((resp) => {
            console.log('client leave result: ', resp);
          },(err) => {
            console.log('client leave failed: ', err);
            //TODO 异常处理
          });
          if (self.localStream){
            self.localStream.mediaStream.getTracks().forEach(track => {
              track.stop()
              console.log("local stream stop success")
              console.log(track)
            })
            self.localStream = null;
            if (document.getElementById('customer')){
              $('#customer').get(0).srcObject = null;
            }
            self.customershow = false;
          }
          if (self.localOriginalCameraStream){
            self.localOriginalCameraStream.mediaStream.getTracks().forEach(track => {
              track.stop()
              console.log("localOriginalCameraStream stop success")
              console.log(track)
            })
            self.localOriginalCameraStream = null;
            if (document.getElementById('customer')){
              $('#customer').get(0).srcObject = null;
            }
            self.customershow = false;
          }
          self.initializationroomdata();
        }
      },

      /*坐席静音和取消静音*/
      audioop(){
        if (this.localPublication){
          var self = this;
          if (self.audiomuted){
            //取消静音
            self.localPublication.unmute('audio').then(function (resp) {
              console.log('取消静音结果',resp);
              self.audiomuted = !self.audiomuted;
            })
          } else{
            //要静音
            self.localPublication.mute('audio').then(function (resp) {
              console.log('静音结果',resp);
              self.audiomuted = !self.audiomuted;
            })
          }
        }else{
          this.$Message.error('你还未加入视频通话');
        }
      },

      /*join成功后设置当前房间用户和remote流信息*/
      getroomuserstreamInfo(resp){
        let remoteStreamArr = resp.remoteStreams;
        var self = this;
        remoteStreamArr.forEach(function (stream,index) {
          // self.streamEvent(stream);//给流添加监听
          console.log('join remote stream',stream)
          if (stream.origin){
            if (stream.attributes&&stream.attributes.type == 'screen'){
              //屏幕共享流--测试下订阅一波
              self.subscribestream(remoteStream,"screen");
            }
            if (stream.attributes == undefined ||stream.attributes.type == 'customer'){
              //坐席端流--测试下订阅一波
              self.subscribestream(stream,"customer");
              self.addstreamtomix(stream.id);
            }
            if (stream.attributes&&stream.attributes.type == 'ai'){
              //坐席端流--测试下订阅一波
              self.agentstreams.push(stream);
              self.subscribestream(stream,'ai');
            }
          }
        })

        //对人员添加监听

      },

      /*推送带水印或者背景的stream*/
      publishwmrbgstream(stream){
        this.aipublishlocalStream(stream,this.aitype);
      },

      createstreamerror(){
        this.$Notice.error({
          title: '温馨提示',
          desc: '当前摄像头不支持视频设置,请检查视频设置',
          duration:10
        });
        //TODO 异常挂断
        imchat.$emit('agenttellcustomer',{id:"agentId",status:'agenterror'});
        this.quitCurrentSession();
      },

      /*publish自己本地的流*/
      aipublishlocalStream(stream,aitypeId){
        this.localStream = stream;
        let videoCodec = {
          name: 'h264',
          profile: 'high',
        }
        let video =
          [{
            codec:videoCodec,
            maxBitrate:this.maxBitrate//vga 800, 720 2000, 1080 4000
          }];

        let audioCodec = {
          name: 'opus',
        }

        let audio = [{
          codec: audioCodec,
        }]

         //判断是否是音频呼叫
        if(this.userData && this.userData.media === 'audio'){
           video = false;
        }
        let option = {
          audio: audio,
          video: video,
        };
        var self = this;
        console.log('publish options：',self.resolution,option);
        console.log('publish stream is',stream);
        this.agentstreams.push(stream);
        publishlocalstream(this.icsClient,stream,option).then(function (publication) {
          publication.originId = stream.id;
          self.localPublication = publication;
          self.localStreamId = stream.id;
          console.log('publish success',publication);
          //TODO 修改agentId
          console.log('agent streams is',self.agentstreams);
          if (document.getElementById(stream.id)){
            $('#'+stream.id).get(0).srcObject = stream.mediaStream;
            $('#'+stream.id).attr('muted','true');
          }

          self.getroomuserstreamInfo(self.roomresp);
          imchat.$emit('readytotalk');
          self.publicationEvent(publication);
          self.addstreamtomix(publication.id);
          if(self.customerClientInfo == 'mini'){
            self.streamout(publication.id,rtmpServer+'/'+self.clientId+self.sessionId,false);
          }
        }).catch(function (error) {
          console.log('publish failed',error);
          imchat.$emit('agenttellcustomer',{id:"agentId",status:'agenterror'});
          self.quitCurrentSession();//退出当前会话
          console.log(error);
        })
      },


      addstreamtomix(streamId){
        var self = this;
        addmix(self.roomId,streamId).then(function (resp) {
          console.log(streamId+'add stream to mix success',resp);
        }).catch(function (error) {
          console.log('add mix failed',error);
        });
      },

      /*重新publish*/
      publicationEvent(publication){
        var self = this;
        let enedListener = (event) => {
          console.log(publication)
          console.log(event)
          if (self.sessionId){
            self.agentstreams = arraytool.removeArraybyoriginid(self.agentstreams,publication);
            console.log('agent publication end agent stream is',self.agentstreams);
            //重新创建流
            self.setstreamandpublish();
          }
        };
        publication.addEventListener('ended', enedListener);
      },

      /*移除publication的监听*/
      removepublicationEvent(publication){
        if (publication){
          publication.clearEventListener('ended');
        }
      },

      /*分享屏幕,*/
      screenshare(){
        if (this.icsClient){
          var self = this;
          createscreenstream("screen").then(function (screenstream) {
            self.screenstream = screenstream;
            self.aipublishscreenstream(screenstream);
          }).catch(function (error) {
            console.log(error);
          })
        } else{
          this.$Message.error("暂不支持");
        }
      },

      /*publish screen application stream*/
      aipublishscreenapplcaitstream(stream){
        var self = this;
        let videoCodec = {
          name: 'h264',
          profile: 'high',
        }
        let  video = [{
          codec:videoCodec,
          maxBitrate:2000//vga 800, 720 2000, 1080 4000
        }]

        let audioCodec = {
          name: 'opus',
        }

        let audio = [{
          codec: audioCodec,
        }]

        audio = false;

        let option = {
          audio: audio,
          video: video,
        };
        console.log('screen stream publish option',option);
        publishscreenstream(this.icsClient,stream,option).then(function (publication) {
          self.screenappstreampublication = publication;
          $('#screenapp').get(0).srcObject = stream.mediaStream;
          // self.recordstream(null,publication.id);
        }).catch(function (error) {
          console.log('publish screen stream failed: ', error);
        })
      },

      /*publish screen stream*/
      aipublishscreenstream(stream){
        var self = this;
        let videoCodec = {
          name: 'h264',
          profile: 'high',
        }
        let  video = [{
          codec:videoCodec,
          maxBitrate:2000//vga 800, 720 2000, 1080 4000
        }]

        let audioCodec = {
          name: 'opus',
        }

        let audio = [{
          codec: audioCodec,
        }]

        audio = false;

        let option = {
          audio: audio,
          video: video,
        };
        console.log('screen stream publish option',option);
        publishscreenstream(self.icsClient,stream,option).then(function (publication) {
          self.screenstreampublication = publication;
          $('#screen').get(0).srcObject = stream.mediaStream;
          $('#screenmark').get(0).srcObject = stream.mediaStream;
          var rtmpServer = localStorage.getItem('rtmpServer');
          var screenrtmpurl = rtmpServer+'/screen'+self.sessionId;
          console.log('screenrtmpurl:',screenrtmpurl);
          if (self.customerClientInfo == 'mini'){
            self.streamout(publication.id,screenrtmpurl,true);
          }
          //screen stream end
          stream.mediaStream.getVideoTracks()[0].onended = function () {
            self.stopscreen(self.screenstreampublication);
          };
        }).catch(function (error) {
          console.log('publish screen stream failed: ', error);
        })
      },

      /*停止屏幕共享流*/
      stopscreenshare(){
        if (this.screenstreampublication){
          var self = this;
          this.screenstreampublication.stop().then(function (resp) {
            self.$Message.success("操作成功");
          });
          this.screenstream = null;
          this.screenstreampublication = null;
        }
      },

      /*给当前client添加监听事件--streamadd/participantjoined/messagereceive/serverdisconnected*/
      addclientEvent(client){
        let streamaddedListener = (eve) =>{
          let remoteStream = eve.stream;
          var self = this;
          console.log('new stream add');
          console.log(remoteStream);
          if (remoteStream.id == this.localStreamId){
            console.log("is my stream");
            return;
          }
          if (remoteStream.attributes == undefined || remoteStream.attributes.type == 'customer'){
            //访客流--测试下订阅一波
            this.subscribestream(remoteStream,"customer");
            this.addstreamtomix(remoteStream.id);
            return;
          }

          if (remoteStream.attributes.type == 'screen'){
            //屏幕共享流--测试下订阅一波
            if (this.screenstreampublication){
              //自己发布的分享流
              return;
            }
            this.subscribestream(remoteStream,"screen");
            this.addstreamtomix(remoteStream.id);
          }

          if (remoteStream.attributes.type == "ai"){
            //判断是否已经
            for (let i =0; i<self.agentstreams.length;i++){
              if (remoteStream.id === self.agentstreams[i].id){
                console.log('have subscribed 😊😊😊');
                return;
              }
            }
            if(self.participant&&remoteStream.origin == self.participant.id){
              console.log(' is me published 😊😊😊');
              return;
            }
            this.agentstreams.push(remoteStream);
            this.subscribestream(remoteStream,remoteStream.id);
          }
        }


        let participantjoinedListener = (eve) => {
          let participant = eve.participant;
          console.log(participant);
        }
        let messagereceivedListener = (eve) => {
        }
        let serverdisconnectedListener = () => {
          console.log('server disconnected');
          //TODO
        }
        this.icsClient.addEventListener("streamadded", streamaddedListener);
        this.icsClient.addEventListener('participantjoined', participantjoinedListener);
        this.icsClient.addEventListener('messagereceived', messagereceivedListener);
        this.icsClient.addEventListener("serverdisconnected", serverdisconnectedListener);
      },

      /*订阅流*/
      subscribestream(stream,type){
        var self = this;
        let audio = true
        let video = true
        if (stream.settings.audio == undefined){
          audio = false;
        }if (stream.settings.video == undefined){
          video = false;
        }
        this.icsClient.subscribe(stream, {
          audio: audio,
          video: video
        })
          .then((subscription) => {
            console.log('subscribe stream success',stream,type);
            console.log(subscription);
            subscription.originId = stream.id;
            if (type == "customer"){
              $('#customer').get(0).srcObject = stream.mediaStream;
              self.customershow = true;
              $('#customer').attr('muted','false');
              self.streamEvent(stream);
              return;
            }
            if (type == "screen"){
              //分享的流
              self.screenstream = stream;
              self.streamEvent(stream);
              $('#screen').get(0).srcObject = stream.mediaStream;
              $('#screen').attr('muted','false');
              return;
            }
            //坐席流
            $('#'+stream.id).get(0).srcObject = stream.mediaStream;
            $('#'+stream.id).attr('muted','false');
            self.streamEvent(stream);
          }, (err) => {
            console.log(`subscribe ${stream.id} failed: ${err}`);
            imchat.$emit('agenttellcustomer',{id:"agentId",status:'agenterror'});
            self.quitCurrentSession();//订阅失败退出
          })
      },
      /*给流添加监听事件 end/activeaudioinputchangeListener/*/
      streamEvent(stream) {
        let enedListener = (event) => {
          console.log(event);
          console.log(stream);
          var self = this;
          //TODO 对stream做操作～～
          if (self.screenstream&&self.screenstream.id === stream.id){
            self.screenstream = null;
            self.screenstreampublication = null;
          }
          if (stream.attributes == undefined || stream.attributes.type === "customer"){
              //访客已经pub end了
              self.$Message.info("访客视频断开！！！");
              $('#customer').get(0).srcObject = null;
          }
          self.agentstreams = arraytool.removeArraybyid(self.agentstreams,stream);
        };
        stream.addEventListener('ended', enedListener);
      },

      /*停止共享*/
      stopscreen(publication){
        console.log("screen stream publication",publication);
        if (this.screenstreampublication){
          if (publication.id == this.screenstreampublication.id){
            var self = this;
            this.screenstreampublication.stop().then(function (resp) {
              self.$Message.success("操作成功");
              imchat.$emit('screenshare','stop');
            });
            this.screenstream = null;
            this.screenstreampublication = null;
          }
        }
        if (this.screenappstreampublication) {
          if (publication.id == this.screenappstreampublication.id){
            var self = this;
            this.screenappstreampublication.stop().then(function (resp) {
              self.$Message.success("操作成功");
            });
            this.screenappstream = null;
            this.screenappstreampublication = null;
          }
        }
      },

      /*zealcomm2:ui op*/
      ringaudioplay(){
        let audio = document.getElementById('ringaudio');
        audio.play();
      },

      ringaudiostop(){
        let audio = document.getElementById('ringaudio');
        audio.pause();
      },



      /*移动*/
      bindMove(self){
        self.$nextTick(()=>{
          const div = self.$refs.div;
          div.onmousedown = function(e){
            // 当前屏幕宽高
            var clientWidth = document.documentElement.clientWidth;
            var winHeight =  document.documentElement.clientHeight;
            var disx = e.pageX - div.offsetLeft;
            var disy = e.pageY - div.offsetTop;
            document.onmousemove = function (e){
              var left = e.pageX - disx;
              var top = e.pageY - disy;
              // if(left > 0 && left < (clientWidth-div.clientWidth) && top > 0 && top < (winHeight-div.clientHeight-10)){
              //     div.style.left = e.pageX - disx + 'px';
              //     div.style.top = e.pageY - disy + 'px';
              // }
              div.style.left = e.pageX - disx + 'px';
              div.style.top = e.pageY - disy + 'px';

            }
            document.onmouseup = function(){
              document.onmousemove = document.onmouseup = null;
            }
          }

          div.oncontextmenu = function(e){ // 点击鼠标右键， 视频框恢复原位
            div.style.left = '25%';
            div.style.top = '62px';
            return false;
          }

        });
      },

      /*zealcomm3:AMS connection*/

      initACC(){
        this.angetClient = new amsClient();
        var amsurl = localStorage.getItem('amsUrl');
        this.angetClient.connect(amsurl,localStorage.getItem('token'));
        var self = this;
        this.angetClient.onError(function (error) {
            console.log(error);
            self.angetClient.close();
            self.gotologin();
        })
      },

      agentready(){
        if (this.sessionId){
          this.$Message.error('会话中不支持操作.');
        } else{
          var self = this;
          this.angetClient.ready(function (status,resp) {
            console.log('agent ready:',status)
            console.log(resp);
            if(status === 'ok'){
              self.appointvalue = null;//预约状态修改
              self.isotherwork = false;
              self.isready = true;
            }else{
              self.gotologin();
              self.$Message.error('就绪错误');
            }
          })
          ///
          // let para = {
          //     groups:['606d71cb34567b87008db62d','606d8f74376ed4afd3f6b319']
          // };
          // this.angetClient.checkIn(para,(status,resp)=>{
          //      console.log('checkin success',status,resp);
          // });
        }
      },

      agentunready(){
        if (this.sessionId){
          this.$Message.error('会话中不支持操作.');
        } else {
          var self = this;
          this.angetClient.notReady(function (status, resp) {
            console.log('agent ready:', status)
            console.log(resp);
            if (status === 'ok') {
              self.isready = false;
            } else {
              self.gotologin();
              self.$Message.error('未就绪错误');
            }
          })
        }
      },

      agenthandup(){
        var self = this;
        this.angetClient.hangup(function (status,resp) {
          console.log('agent hangup:',status)
          console.log(resp);
          if(status === 'ok'){
            self.$Message.success('会话结束成功');
          }else{
            //self.$Message.error('会话结束失败');
            //TODO异常处理
          }
        })
      },

      agentlogout(){
        if (this.sessionId){
          this.$Message.error('会话中不支持操作.');
        } else {
          var self = this;
          this.angetClient.logout(function (status, resp) {
            console.log('logout: ', status);
            if (status === 'ok') {
              self.islogin = false;
              self.isready = false;
              self.agentId=null;
              clearInterval(self.amsinterval);
              self.amsinterval = null;
              self.initializationdata();
            } else {
              self.$Message.error('登出错误');
              self.gotologin();
            }
          });
        }
      },

      agentlogin(){
        this.initACC();
        var self = this;
        this.angetClient.onConnect(function(a){
          console.log('ams onConnect', a);
          if (!self.islogin){
            let id = localStorage.getItem('userId');
            let name = localStorage.getItem('name');
            let org = localStorage.getItem('org');
            let data = {agent: {id: id, name: name, org: org
              },skills:[]};
            self.angetClient.login(function(status, resp){
              console.log('login: ', status, JSON.stringify(resp));
              if(status === 'ok'){
                self.agentId = resp.agentId;
                self.ticket = resp.ticket;
                self.islogin = true;
                var ams_ticket_refreshtime = resp.refershTicketTime;
                self.amsinterval = setInterval(function () {
                  self.angetClient.refreshTicket(function (status,resp) {
                    console.log(status);
                    if (status === "ok"){
                      console.log(resp);
                      self.ticket = resp.ticket;
                      console.log('new ticket=',self.ticket);
                    }
                  })
                },ams_ticket_refreshtime);
              }else{
                self.islogin = false;
                self.$Message.error('登入错误');
                self.gotologin();
              }
            });
            self.angetClient.onRing(function(data){
              console.log('ring data',data);
              self.onring(data);
            });
            self.angetClient.onStopRinging(function (data) {
              console.log('customer onStopRinging');
              console.log(data);
              self.ringaudiostop();
              self.onRing = false;
            })
          }else{
            self.resumeconnect();
          }

        });
        this.angetClient.onDisconnect(function(a){
          /*重连失败*/
          console.log('ams onDisconnect', a);
        })
      },



      /*接到call*/
      onring(data){
        this.sessiondata = data;
        this.userData = data.userData;
        console.log(data);
        this.ringaudioplay();
        this.onRing = true;
      },


      answercall(){
        var self = this;
        let data = this.sessiondata;
        this.angetClient.answerCall(function (status,resp) {
          console.log(status);
          console.log(resp);
          if (status === "ok"){
            self.sessionId = data.sessionId;
            self.$refs.agentop.sessionId = self.sessionId;
            self.ccsurl  = data.url;
            imchat.$emit('agentjoinccssession',data);
          }else{
            //TODO 接听失败
            self.$Message.error('接听失败！！！');
          }
        })
        self.onRing = false;
        this.ringaudiostop();
      },

      joinSession(data){
        console.log('join session data',data);
        this.$refs.agentop.sessionId = data.sessionId;
        imchat.$emit('agentjoinccssession',data);
        this.showManagementView = false;
        // imchat.$emit('joinSession',data);
        // this.roomId = data.roomId;
        // this.roomToken = data.roomToken;
        // console.log('roomid===',this.roomId);
        // console.log('roomtoken===',this.roomToken);
        // this.joinroom();
      },




      rejectcall(){
        var self = this;
        this.angetClient.rejectCall(function (status) {
          if(status === "ok"){
          }
          self.onRing = false;
          console.log('reject call',status);
        })
        this.ringaudiostop();
      },


      resumeconnect(){
        var self = this;
        if (self.angetClient){
          console.log('old ticket',self.ticket);
          self.angetClient.resumeConnection(self.ticket, function(status, resp){
            console.log('resumeconnection',status);
            console.log(resp);
            if(status === 'ok'){
              console.log('resumeConnection:', JSON.stringify(resp));
              self.ticket = resp.ticket;
            } else {
              /*todo 刷新失败的处理*/
            }
          });
        }
      },



      /*zealcomm4:setting*/

      /*选择水印图*/
      addwater(){
        var self = this;
        this.$Modal.success({
          title: '选择水印图片',
          render: (h) => {
            return h(watermark, {
              ref: 'watermark',
            })
          },
          width: 800,
          closable: false,
          okText: "确定",
          cancelText: "取消",
          onOk() {
            if (this.$refs.watermark.type==1){
                //640
                if (this.$refs.watermark.index==1){
                  localStorage.setItem('watermarkimage','static/image/water6401.png');
                }else if (this.$refs.watermark.index==2){
                  localStorage.setItem('watermarkimage','static/image/water6402.png');
                } else if (this.$refs.watermark.index==3){
                  localStorage.setItem('watermarkimage','static/image/water6403.png');
                }
            } else if (this.$refs.watermark.type==2) {
                //720
                if (this.$refs.watermark.index == 1) {
                  localStorage.setItem('watermarkimage', 'static/image/water12801.png');
                } else if (this.$refs.watermark.index == 2) {
                  localStorage.setItem('watermarkimage', 'static/image/water12802.png');
                } else if (this.$refs.watermark.index == 3) {
                  localStorage.setItem('watermarkimage', 'static/image/water12803.png');
                }
            }
            else if (this.$refs.watermark.type==3) {
                  //1080
                  if (this.$refs.watermark.index == 1) {
                    localStorage.setItem('watermarkimage', 'static/image/water19201.png');
                  } else if (this.$refs.watermark.index == 2) {
                    localStorage.setItem('watermarkimage', 'static/image/water19202.png');
                  } else if (this.$refs.watermark.index == 3) {
                    localStorage.setItem('watermarkimage', 'static/image/water19203.png');
                  }
                }
            self.isAddWatermark = true;
            self.$Message.success('设置水印成功，接通视频后可查看效果');
          },
          onCancel(){

          }
        });
      },

      /*选择背景图*/
      addbackgroup(){
        var self = this;
        this.$Modal.success({
          title: '选择背景图片',
          render: (h) => {
            return h(bg, {
              ref: 'bg',
            })
          },
          width: 800,
          closable: false,
          okText: "确定",
          cancelText: "取消",
          onOk() {
            if (this.$refs.bg.type==1){
              localStorage.setItem('bgimage','static/image/bg640'+this.$refs.bg.index+'.png');
            } else if (this.$refs.bg.type==2) {
              //720
              localStorage.setItem('bgimage','static/image/bg1280'+this.$refs.bg.index+'.png');
            }
            else if (this.$refs.bg.type==3) {
              localStorage.setItem('bgimage','static/image/bg1920'+this.$refs.bg.index+'.png');
            }
            self.isReplaceBackground = true;
            self.Red = this.$refs.bg.red;
            self.Green = this.$refs.bg.green;
            self.Blue = this.$refs.bg.blue;
            console.log(self.Red+':'+self.Green+":"+self.Blue);
            self.$Message.success('设置背景成功，接通视频后可查看效果');
          },
          onCancel(){

          }
        });

      },

      /*坐席设置最大码率*/
      choosemaxbirtate(value){
        console.log(value);
        this.maxBitrate = parseInt(value);
      },

      setbirtate(value){
        this.maxBitrate = value;
        console.log('birtate',this.maxBitrate);
        console.log(typeof (this.maxBitrate));
      },

      setresolution(value){
        this.resolution = value;
        console.log('resolution',this.resolution);
      },


      /*zealcomm5:Business functions*/


      /*去登录页面*/
      gotologin(){
        var self = this;
        this.$Modal.confirm({
          title: '温馨提示',
          content:'请重新登录',
          width: 600,
          closable: false,
          okText: "确定",
          cancelText: "取消",
          onOk() {
            self.$router.push('/');
          },
          onCancel(){

          }
        });
      },

      /*获取客户表单信息*/
      getformdata(){
        if (this.sessionId) {
          var self = this;
          getsessionformdata(self.sessionId).then(function (resp) {
            console.log('form data =',resp);
            if (resp.status == 200){
              if (resp.data.code == 200){
                self.formdata = resp.data.data;
                self.$refs.aileft.showformdata = true;
              }else{
                self.$Message.error('暂无访客提交的信息');
              }
            }else{
              self.$Message.error('暂无访客提交的信息');
            }
          })
        }else{
          this.$Message.error('暂无会话');
        }
      },

      /*收集用户信息*/
      collectionform(){
        var self = this;
        this.$Modal.confirm({
          title: '收集用户信息',
          render: (h) => {
            return h(Userinfo, {
              ref: 'Userinfo',
            })
          },
          width: 600,
          closable: false,
          okText: "确定",
          cancelText: "取消",
          onOk() {
            console.log(this.$refs.Userinfo.name);
            var name = this.$refs.Userinfo.name;
            var id = this.$refs.Userinfo.id;
            var mobile = this.$refs.Userinfo.mobile;
            var category = this.$refs.Userinfo.category;
            var address = this.$refs.Userinfo.address;
            var company = this.$refs.Userinfo.company;
            if (name==null||id==null||mobile==null||category==null||address==null||company==null){
              self.$Message.error("请完善信息");
            }else{
              //把客户信息发送给客户，，然后客户提交到server上
              var info = {
                name:name,
                ID:id,
                mobile:mobile,
                productCategory:category,
                address:address,
                company:company,
                collect:1,//收集信息
              };
              imchat.$emit('agentcollectioninfo',info);
            }
          },
          onCancel(){

          }
        });
      },

      /*手机更新用户提交的照片*/
      collectionPic(type){
        /*身份证前后，银行卡，自拍照*/
        imchat.$emit('collectionPic',type);
      },



      /*初始化业务数据*/
      initializationdata(){
        this.formdata = null;
        this.forminfodata = null;
        this.userId = null;
        this.username = null;
        this.recorddata = [];
        this.chatList = [];
        this.captureImage = [];
        this.ccsurl = null;
        this.sessionId = null;
        this.clientId = null;
        this.audiomuted = false;
        if (this.$refs.agentop) {
          this.$refs.agentop.sessionId = null;
        }
      },

      initializationroomdata(){
        this.participant = null;
        this.agentstreams = new Array();
        this.roomresp = null;
        this.recordstreamList = [];
        this.icsClient = null;
        this.roomId = null;
        this.roomToken = null;
        this.localStream = null;
        this.localStreamId = null;
        this.localPublication = null;
        this.screenstream = null;
        this.screenstreampublication = null;
        this.screenappstream = null;
        this.screenappstreampublication = null;
      },



      //结束会话需要判断当前状态
      endsession(){
        this.quitCurrentSession();
      },


      /*访客挂断*/
      customerhangup(){
        var self = this;
        self.$Modal.success({
          title: '访客已挂断！',
          okText:"确定",
          onOk: () => {
            self.quitCurrentSession();
          }
        });
      },

      /*访客加入房间失败挂断*/
      customerjoinroomerror(){
        var self = this;
        self.$Modal.success({
          title: '访客加入视频失败，已挂断',
          okText:"确定",
          onOk: () => {
            self.quitCurrentSession();
          }
        });
      },



      /*坐席端截图*/
      snapshot(){
       // this.captureCustomerImage();
        imchat.$emit('clientsnapshot');
      },

      /*发送指令邀请客户拍照*/
      photoGuideBox(){
        imchat.$emit('photoGuideBox');
      },

      //截图客户的图
      captureCustomerImage(){
        let video = document.getElementById('customer');
        let canvas = document.getElementById('canvas');
        console.log(video);
        console.log(canvas);
        canvas.style.width = video.clientWidth;
        canvas.style.height = video.clientHeight;
        let context = canvas.getContext('2d');
        console.log(video.clientWidth)
        console.log(video.clientHeight)
        // context.drawImage(video, 0, 0, video.clientWidth, video.clientHeight);
        context.drawImage(video, 0, 0, video.clientHeight*3/4, video.clientHeight);
        var c = document.getElementById("canvas");
        var image = c.toDataURL("image/png");
        this.captureImage = image;

        //上传到服务器
        let para = {
          "customerId":localStorage.getItem('userId'),
          "image":image
        }
        var self = this;
        saveimg(para).then(function (resp) {
          if (resp.status == 200){
            if (resp.data.code == 200){
              let url = resp.data.data.url;
              //发送给访客拍摄的照片
              // imchat.$emit('snapshot',url);
            }else {
              self.$Message.error('拍照失败');
            }
          }
        });
      },

      /*推送视频*/
      sendvideo(){
        this.$Modal.confirm({
          title: '选择发送的视频文件',
          render: (h) => {
            return h(SendVideo, {
              ref: 'SendVideo',
            })
          },
          width: 800,
          closable: false,
          okText: "确定",
          cancelText: "取消",
          onOk() {
            console.log(this.$refs.SendVideo.linkurl);
            imchat.$emit('sendvideo',this.$refs.SendVideo.linkurl);
          },
          onCancel(){

          }
        });
      },

      /*推送链接*/
      sendlink(){
        this.$Modal.confirm({
          title: '选择发送的链接',
          render: (h) => {
            return h(SendLink, {
              ref: 'SendLink',
            })
          },
          width: 600,
          closable: false,
          okText: "确定",
          cancelText: "取消",
          onOk() {
            console.log(this.$refs.SendLink.linkurl);
            imchat.$emit('sendlink',this.$refs.SendLink.linkurl);
          },
          onCancel(){

          }
        });
      },


      /*正在手写签名*/
      showhandSign(data){
        var self = this;
        this.$Modal.info({
          title: '访客正在手写签名...',
          render: (h) => {
            return h(RemoteHandSign, {
              ref: 'RemoteHandSign',
            })
          },
          width: 400,
          closable: false,
          okText: "关闭",
          cancelText: "取消",
          onOk() {
            self.isHandSign = false;
          },
          onCancel(){

          }
        });
      },



      /*设置技能组*/
      setskill(){
        var self = this;
        this.$Modal.confirm({
          title: '选择技能组',
          render: (h) => {
            return h(SkillList, {
              ref: 'SkillList',
            })
          },
          width: 600,
          closable: false,
          okText: "确定",
          cancelText: "取消",
          onOk() {
            let value = this.$refs.SkillList.skillvalue;
            var skilltype;
            if (value === "查询服务") {
              skilltype = "1";
            }else if (value === "办卡服务") {
              skilltype = "2";
            }else if (value === "贷款服务") {
              skilltype = "3";
            }else if (value === "高级服务") {
              skilltype = "4";
            }
            updateskill(self.agentId,skilltype).then(function (resp) {
               console.log('update success',resp);
               self.skillvalue = value;
            }).catch(function (error) {
              console.log("update skill failed",error);
            })
            console.log(this.$refs.SkillList.skillvalue);
          },
          onCancel(){

          }
        });
      },

      //坐席预约
      appoint(){
        var self = this;
        this.$Modal.confirm({
          title: '选择预约项',
          render: (h) => {
            return h(Appointment, {
              ref: 'Appointment',
            })
          },
          width: 600,
          closable: false,
          okText: "确定",
          cancelText: "取消",
          onOk() {
            console.log('appointment,,,');
            console.log(this.$refs.Appointment.appointvalue);
            console.log(this.$refs.Appointment.restreason);
            //enableAppointStates = ['notReady', 'afterWork', 'otherWork'];
            var appointState;
            var appointvalue = this.$refs.Appointment.appointvalue;
            if (this.$refs.Appointment.appointvalue=="小休"){
              appointState = "otherWork";
            }else if (this.$refs.Appointment.appointvalue=="整理"){
              appointState = "afterWork";
            }else if (this.$refs.Appointment.appointvalue=="其他"){
              appointState = "notReady";
            }
            let data = {appointState: appointState, reason:this.$refs.Appointment.restreason};
            console.log('appoint data',data);
            self.angetClient.appoint(data,function (resp) {
              console.log(resp);
              self.appointvalue = appointvalue;
              self.isready = false;
            });
          },
          onCancel(){

          }
        });
      },

      otherwork(){
        var self = this;
        this.$Modal.confirm({
          title: '请选择小休原因',
          render: (h) => {
            return h(Otherwork, {
              ref: 'Otherwork',
            })
          },
          width: 600,
          closable: false,
          okText: "确定",
          cancelText: "取消",
          onOk() {
            console.log(this.$refs.Otherwork.reason);
            let data  = {reason: this.$refs.Otherwork.reason };
            self.angetClient.otherWork(data,function (resp) {
              console.log(resp);
              self.isotherwork = true;
              self.isready = false;
            });
          },
          onCancel(){

          }
        });
      },

      /*共享屏幕标注*/
      screenmark(){
        this.showscreenmark = true;
      },

      closescreenmark(){
        this.showscreenmark = false;
        this.sendwhiteboardmessage("endmark");
      },


      /*退出当前会话*/
      quitCurrentSession(){
        var self = this;
        imchat.$emit('quitccs',function (resp) {
          console.log(resp);
        });
        let para ={
          "sessionId":this.sessionId,
          "formId": localStorage.getItem('formid')
        };
        savesessionform(para).then(function (resp) {
          localStorage.setItem('formid',"-1");
          console.log('save session form result',resp);
        })
        self.agenthandup();
        self.initializationdata();
        self.leaveclient();
      },

     /**
      * 强拆其他坐席
      */
     removeAgent(){
          imchat.$emit('removeAgent');
          this.$Message.info('系统将强拆其他坐席的会话');
     },

      //转接坐席
      tranferagent(needleave){
        var title = needleave?"转接坐席设置":"三方坐席设置";
        var self = this;
        this.$Modal.confirm({
          title: title,
          render: (h) => {
            return h(Transfer, {
              ref: 'Transfer',
            })
          },
          width: 600,
          closable: false,
          okText: "确定",
          cancelText: "取消",
          onOk() {
             var agentId = this.$refs.Transfer.agentId;
             var skill = this.$refs.Transfer.skill;
             var media = (self.userData &&  self.userData.media)?self.userData.media:'video';
             console.log(agentId);
             console.log(skill);
             if (agentId == null){
               agentId = '*';//盲转
             }
             let option = {
               agentId:agentId,
               skill:skill,
               userData:{
                 byAgent:self.agentId,
                 virtualAgentType:"registered",
                 media:media
               }
             };
             let info = {
                data:option,
                needleave:needleave
             };
             imchat.$emit('transferagent',info);
          },
          onCancel(){

          }
        });
      },

      /** 
      * 坐席咨询
      */
      consulting(){       
        var title = "请输入咨询的第三方坐席的工号";
        var self = this;
        this.$Modal.confirm({
          title: title,
          render: (h) => {
            return h(Transfer, {
              ref: 'Transfer',
            })
          },
          width: 600,
          closable: false,
          okText: "确定",
          cancelText: "取消",
          onOk() {
             var agentId = this.$refs.Transfer.agentId;
             var skill = this.$refs.Transfer.skill;
             console.log(agentId);
             console.log(skill);
             if (agentId == null){
               agentId = '*';//盲转
             }
             let option = {
               agentId:agentId,
               skill:skill,
               userData:{
                 byAgent:self.agentId,
                 virtualAgentType:"registered",
                 media:self.userData.media
               }
             };
             let info = {
                data:option,
                needleave:false
             };
             imchat.$emit('transferagent',info);
             //告诉访客
             imchat.$emit('sendCustomText','startConsulting');
             self.isConsulting = true;
             self.$Message.info('正在咨询中...');
          },
          onCancel(){

          }
        });
           
      },

      //停止咨询
      stopConsulting(){
           imchat.$emit('sendCustomText','stopConsulting');
           this.isConsulting = false;
           this.$Message.info('停止咨询，恢复和访客的通话')
      },

      /*获取用户刚开始进来提交的表单信息*/
      getforminfodata(formid){
        var self = this;
        if (formid != "-1"){
          localStorage.setItem('formid',formid);
          getuserforminfo(formid).then(function (resp) {
            //用户提交的表单信息
            if (resp.data.code == 200){
              self.forminfodata = resp.data.data;
            }
          }).catch(function (error) {
          });
        }else{
          self.$Notice.success({
            title: '温馨提示',
            desc: '当前客户未提交资料～',
            duration:10
          });
        }
      },


  }}
</script>

<style scoped>

  .headtitle{
    float: left;
    color: white;
    font-size: 16px;
    margin-right: 50px;
  }

  .headop{
    float: right;
    margin-right: 10px;
    margin-top: 17px;
  }

  .z-headop{
    float: right;
    margin-right: 10px;
    /*width: 1000px;*/
    height: 50px;
    margin-top: 7px;
  }


  .headbtn{
    width:120px;
    height:30px;
    border:1px solid rgba(125,179,236,1);
    border-radius:4px;
    line-height: 30px;
    font-size:14px;
    font-family:PingFang SC;
    font-weight:400;
    color:rgba(255,255,255,1);
  }


  .headopgray{
    float: right;
    margin-right: 10px;
    margin-top: 17px;
    background-color: #2c3e50;
    color: white;
  }

  .setting{
    float: right;
    margin-right: -20px;
    margin-top: 20px;
    width: 25px;
    height: 25px;
  }

  .op{
    display: flex;
    flex-direction: row;
    align-content: space-between;
    align-items: flex-start;
  }

  .aiop{
    width: 100%;
    height: 120px;
    /*border: 0.5px solid #2b85e4;*/
    margin-top: 20px;
    border-radius: 10px;
  }

  /*.customervideo{*/
  /*width: 100%;*/
  /*height: 360px;*/
  /*}*/

  .totalvideo{
    width: 100%;
    height: 360px;
  }

  .halfvideo{
    width: 50%;
    height: 360px;
  }

  /*.videoshow{*/
  /*position: relative;*/
  /*width: 40%;*/
  /*height: 360px;*/
  /*left: 30%;*/
  /*background-color: #515a6e;*/
  /*top: 64px;*/
  /*}*/

  .aivideo{
    position: absolute;
    width: 200px;
    height: 150px;
    z-index: 100;
    margin-left: -50%;
    background-color: #515a6e;
  }

  .ai2video{
    position: absolute;
    width: 200px;
    height: 150px;
    z-index: 100;
    margin-left: -50%;
    margin-top: 150px;
    background-color: #515a6e;
  }

  .aiaudeo{
    position: absolute;
    width: 200px;
    height: 20px;
    z-index: 100;
    margin-left: -50%;
    background-color: #515a6e;
  }

  .ai2audio{
    position: absolute;
    width: 200px;
    height: 20px;
    z-index: 100;
    margin-left: -50%;
    margin-top: 150px;
    background-color: #515a6e;
  }

  .aihalfvideo{
    position: absolute;
    width: 200px;
    height: 150px;
    z-index: 100;
    margin-left: -50%;
    background-color: #515a6e;
  }

  .col{
    display: flex;
    flex-direction: column;
    align-content: center;
    align-items: center;
    margin-top: 30px;
    margin-left: 10px;
    margin-right: 10px;
  }

  .img{
    width: 40px;
    height: 40px;
  }

  .videoshow {
    width: 40%;
    position: absolute;
    cursor: move;
    z-index: 5;
    left: 32%;
    top: 64px;
    background-color: rgba(249,249,249,1);
  }

  .customervideo{
    width: 100%;
    height: 350px;
    object-fit: contain;
  }

  .defaultcustomer{
    width: 95%;
    height: 350px;
    background-color: white;
  }

  .customerrenwu{
    width: 200px;
    height: 200px;
    margin-top: 75px;
  }
  .defaultagent{
    width: 100%;
    height: 350px;
  }

  .agentdiv{
     width: 160px;
     height: 120px;
     margin: 0 auto;
     margin-top: 20px;
     background:rgba(249,249,249,1);
  }

  .agentrenwu{
    width: 80px;
    height: 80px;
    margin-top: 20px;
  }




  .otherStream{
    width:40%;
    height:350px;
    background:rgba(255,255,255,1);
    /*border-radius:10px;*/
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-content: center;
  }

  .otherStreamvideo{
    width: 90%;
    height: 100px;
    margin-left: 5%;
    margin-top: 10px;
  }

  .settingview{
    /*width: 200px;*/
    /*height: 2000px;*/
    /*float: right;*/
    position: absolute;
    right: 50px;
    top: 70px;
    z-index: 100;
  }

  .screenmark{
    width: 100%;
    height: 100%;
    position: fixed;
    z-index: 10;
  }

  .handsign{
    width: 50%;
    height: 500px;
    left: 50%;
    position: fixed;
    z-index: 10;
  }


</style>
